package com.globalwave.filemanage{
    import flash.display.Sprite;
    import flash.events.*;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    import flash.net.URLRequest;
    import mx.controls.ProgressBar;
    import flash.utils.Timer;

    public class SoundPlayer extends Sprite {
       // private var url:String = "MySound.mp3";
        private var channel:SoundChannel;
		private var progbar:ProgressBar;
		private var soundFactory:Sound;
		private var positionTimer:Timer;
        public function SoundPlayer() {
           
        }
        public function set progressBar(pb:ProgressBar) :void{
        	progbar = pb;
        }
        public function load(url:String):void {
        	var request:URLRequest = new URLRequest(url);
            soundFactory = new Sound();
            soundFactory.addEventListener(Event.COMPLETE, completeHandler);
            soundFactory.addEventListener(Event.ID3, id3Handler);
            soundFactory.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            soundFactory.addEventListener(ProgressEvent.PROGRESS, progressHandler);

            soundFactory.load(request);
            if(progbar)
           	progbar.mode = "manual";
        }
        public function play():void{
        	stop();
        	channel = soundFactory.play();
        	channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
        	positionTimer = new Timer(50);
            positionTimer.addEventListener(TimerEvent.TIMER, positionTimerHandler);
            positionTimer.start();
   
        }
        private function positionTimerHandler(event:TimerEvent):void {
            trace("positionTimerHandler: " + channel.position.toFixed(2));
        }
        public function stop():void{
        	if(!channel)
        	return;
        	channel.stop();	
        	positionTimer.stop();
        }
 		public function pause():void{
 			if(!channel)
        	return;
        	channel.stop();
        }
        private function completeHandler(event:Event):void {
            trace("completeHandler: " + event);
            progbar.mode = "event";
        }

        private function id3Handler(event:Event):void {
            trace("id3Handler: " + event);
        }

        private function ioErrorHandler(event:Event):void {
            trace("ioErrorHandler: " + event);
            positionTimer.stop(); 
        }

        private function progressHandler(event:ProgressEvent):void {
            trace("progressHandler: " + event);
          	progbar.setProgress(event.bytesLoaded, event.bytesTotal);
        }
        private function soundCompleteHandler(event:Event):void {
            trace("soundCompleteHandler: " + event);
            positionTimer.stop();
        }
    }
}